package org.triumphxx.springboot.beansearcher.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: wangyp
 * @Date: 2023/7/23
 * @Time: 16:59
 * @Desc: 将对象转换为Map
 **/

public class MapUtil {

    public static Map<String, Object> toMap(Object bean) {
        Map<String, Object> map = new HashMap<>();
        Class<?> beanClass = bean.getClass();
        while (beanClass != Object.class) {
            for (Field field : beanClass.getDeclaredFields()) {
                field.setAccessible(true);
                try {
                    // 将下划线转换为中划线
                    String name = field.getName().replace('_', '-');
                    map.put(name, field.get(bean));
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
            beanClass = beanClass.getSuperclass();
        }
        return map;
    }
}
